package com.shiro;

import org.apache.shiro.authc.*;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.subject.SimplePrincipalCollection;

/**
 * 自定义Realm
 * 重写的方法的执行循序是 supports()->getAuthenticationInfo()
 */
public class MyRealm implements Realm{

    @Override
    public String getName() {
        System.out.println("method getName is run");
        return "myrealm";//用于生成AuthenticationInfo
    }

    @Override
    public boolean supports(AuthenticationToken authenticationToken) {
        System.out.println("method supports is run");
        if(authenticationToken instanceof UsernamePasswordToken){
            return true;
        }else{
            throw new AuthenticationException("证书不是标准证书");
        }
    }

    /**
     * AuthenticationInfo用于存储验证过的subject的信息与AuthenticationToken的不同时后者用于存储未验证的信息
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    public AuthenticationInfo getAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("method getAuthenticationInfo is run");
        System.out.println(authenticationToken.getPrincipal().getClass());
        System.out.println(authenticationToken.getCredentials().getClass());
        SimplePrincipalCollection principalCollection=new SimplePrincipalCollection();
        SimpleAuthenticationInfo authenticationInfo=new SimpleAuthenticationInfo(authenticationToken.getPrincipal(),authenticationToken.getCredentials(),getName());
        return authenticationInfo;
    }
}
